package JzOffer.jz41;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 * @author 张取
 * @version 1.0
 * @date 2022/1/7 下午9:17
 * JzOffer.jz41
 */

public class Solution01 {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入窗口大小：");
        int size = scanner.nextInt();
        MovingAverage01 obj = new MovingAverage01(size);
        int val;
        double res = 0;
        while(true){
            System.out.println("==================");
            val = scanner.nextInt();
            res = obj.next(val);
            System.out.println(res);
        }
    }
}

class MovingAverage01 {

    private Queue<Integer> queue;
    private final int size;

    /** 初始化数据结构 */
    public MovingAverage01(int size){
        queue = new LinkedList<>();
        this.size = size;
    }

    /** 遍历队列，时间复杂度为O(n) */
    public double next(int val){
        double sum = 0;
        if(queue.size() >= this.size){
            queue.poll();
        }
        queue.offer(val);
        //集合方式遍历栈，元素不会被移除
        for (Integer ele : queue){
            sum += ele;
        }
        return sum / queue.size();
    }
}
